package com.ruoyi.safe.service.impl;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.IdUtil;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.common.utils.DictUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.safe.domain.BizEnterCheck;
import com.ruoyi.safe.domain.BizEnterTask;
import com.ruoyi.safe.domain.BizProjectCheckRecord;
import com.ruoyi.safe.domain.dto.ProjectSearchDTO;
import com.ruoyi.safe.domain.vo.BizEnterCheckProjectVO;
import com.ruoyi.safe.domain.vo.CommonProjectVO;
import com.ruoyi.safe.mapper.BizEnterTaskMapper;
import com.ruoyi.safe.mapper.BizProjectCheckRecordMapper;
import com.ruoyi.safe.mapper.CommonProjectMapper;
import com.ruoyi.safe.service.IBizEnterCheckService;
import com.ruoyi.safe.service.IBizProjectCheckRecordService;
import com.ruoyi.system.mapper.SysUserMapper;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.safe.mapper.BizEnterCheckProjectMapper;
import com.ruoyi.safe.domain.BizEnterCheckProject;
import com.ruoyi.safe.service.IBizEnterCheckProjectService;

/**
 * 企业检查-项目Service业务层处理
 *
 * @author ruoyi
 * @date 2023-12-06
 */
@Service
public class BizEnterCheckProjectServiceImpl implements IBizEnterCheckProjectService
{
    @Autowired
    private BizEnterCheckProjectMapper bizEnterCheckProjectMapper;
    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    private CommonProjectMapper commonProjectMapper;
    @Autowired
    private BizEnterTaskMapper bizEnterTaskMapper;
    @Autowired
    private BizProjectCheckRecordMapper bizProjectCheckRecordMapper;
    @Autowired
    IBizProjectCheckRecordService bizProjectCheckRecordService;
    @Autowired
    IBizEnterCheckService bizEnterCheckService;

    /**
     * 查询企业检查-项目
     *
     * @param id 企业检查-项目主键
     * @return 企业检查-项目
     */
    @Override
    public BizEnterCheckProjectVO selectBizEnterCheckProjectById(Long id, SysUser user)
    {
        BizEnterCheckProject bizEnterCheckProject = bizEnterCheckProjectMapper.selectBizEnterCheckProjectById(id);
        setListParamNames(Collections.singletonList(bizEnterCheckProject));
        BizEnterCheckProjectVO vo = getBizEnterCheckProjectVO(user, bizEnterCheckProject);
        setCheckProjectRecord(user, vo);
        setEnterCheck(user, vo);
        return vo;
    }

    private void setEnterCheck(SysUser user, BizEnterCheckProjectVO vo) {
        BizEnterCheck enterCheck = bizEnterCheckService.selectBizEnterCheckById(vo.getBizEnterCheckId());
        vo.setBizEnterCheck(enterCheck);
        vo.setCheckBasisName(DictUtils.getDictLabel("check_according", enterCheck.getCheckBasis()));
    }

    /**
     * 查询企业检查-项目列表
     *
     * @param bizEnterCheckProject 企业检查-项目
     * @return 企业检查-项目
     */
    @Override
    public List<BizEnterCheckProjectVO> selectBizEnterCheckProjectList(BizEnterCheckProject bizEnterCheckProject, SysUser user)
    {
        List<BizEnterCheckProject> list
                = bizEnterCheckProjectMapper.selectBizEnterCheckProjectList(bizEnterCheckProject);
        setListParamNames(list);

        List<BizEnterCheckProjectVO> voList = new ArrayList<>();
        list.forEach(item -> {
            BizEnterCheckProjectVO vo = getBizEnterCheckProjectVO(user, item);
            voList.add(vo);
        });

        return voList;
    }

    @NotNull
    private BizEnterCheckProjectVO getBizEnterCheckProjectVO(SysUser user, BizEnterCheckProject item) {
        BizEnterCheckProjectVO vo = new BizEnterCheckProjectVO();
        BeanUtil.copyProperties(item, vo);
        BizEnterTask task = new BizEnterTask();
        task.setBizEnterCheckProjectId(item.getId());
        List<BizEnterTask> taskList = bizEnterTaskMapper.selectBizEnterTaskList(task);
        BizEnterTask dbData = taskList.get(0);
        List<BizProjectCheckRecord> records = bizProjectCheckRecordMapper
                .selectListByProjectCheckId(dbData.getBizEnterCheckProjectId());
        dbData.setHiddenNumber(
                Math.toIntExact(records.stream().filter(r -> Stream.of("1", "2", "3")
                        .anyMatch(s -> s.equals(r.getHiddenDangerStatus()))).count()));
        vo.setBizEnterTask(dbData);
        vo.setHasAddRecordPermission(item.getGroupLeader().contains(String.valueOf(user.getUserId()))
                || item.getGroupMember().contains(String.valueOf(user.getUserId())));
        List<CommonProjectVO> projectVOS = commonProjectMapper.selectCommonProjectList(new ProjectSearchDTO());
        projectVOS.forEach(p -> {
            if (p.getName().equals(item.getCheckProjectIdsList().get(0))) {
                vo.setDeptName(p.getDeptName());
            }
        });
        return vo;
    }

    private void setCheckProjectRecord(SysUser user, BizEnterCheckProjectVO vo) {
        //当前id下的所有隐患记录
        List<BizProjectCheckRecord> bizProjectCheckRecords = bizProjectCheckRecordService.selectCheckRecordListById(vo.getId());
        List<BizProjectCheckRecord> myBizProjectCheckRecords
                = bizProjectCheckRecords.stream()
                .filter(bizProjectCheckRecord -> user.getUserName().equals(bizProjectCheckRecord.getCheckPeople()))
                .collect(Collectors.toList());
        //我的待办的隐患数量
        long inHandDangerCount = myBizProjectCheckRecords.stream().filter(a -> {
            boolean flag = "2".equals(a.getHiddenDangerStatus()) || "1".equals(a.getHiddenDangerStatus());
            return flag && a.getCheckPeople().equals(user.getUserName());
        }).count();
        vo.setInHandDangerCount(inHandDangerCount);
        vo.setBizProjectCheckRecords(bizProjectCheckRecords);
        vo.setMyBizProjectCheckRecords(myBizProjectCheckRecords);
        vo.setFindDangerCount((long) bizProjectCheckRecords.size());
        vo.setImportHiddenDangerCount(bizProjectCheckRecords.stream()
                .filter(r -> "2".equals(r.getAccidentHidden())).count());
    }

    private void setListParamNames(List<BizEnterCheckProject> bizEnterCheckProjectList) {
        bizEnterCheckProjectList.forEach(item -> {
            //赋值参检人员
            List<String> memberList = new ArrayList<>();
            Arrays.stream(item.getGroupMember().split(",")).forEach(a -> {
                memberList.add(sysUserMapper.selectUserById(Long.valueOf(a)).getNickName());
                item.setGroupMemberList(memberList);
            });
            //赋值参见组长
            List<String> leaderList = new ArrayList<>();
            Arrays.stream(item.getGroupLeader().split(",")).forEach(o -> {
                leaderList.add(sysUserMapper.selectUserById(Long.valueOf(o)).getNickName());
                item.setGroupLeaderList(leaderList);
            });
            //赋值检查项目
            List<String> projectIdList = new ArrayList<>();
            Arrays.stream(item.getCheckProjectIds().split(",")).forEach(p -> {
                projectIdList.add(commonProjectMapper.selectCommonProjectById(Long.valueOf(p)).getName());
                item.setCheckProjectIdsList(projectIdList);
            });
        });
    }

    /**
     * 新增企业检查-项目
     *
     * @param bizEnterCheckProject 企业检查-项目
     * @return 结果
     */
    @Override
    public void insertBizEnterCheckProject(BizEnterCheckProject bizEnterCheckProject, SysUser user)
    {

        Arrays.stream(bizEnterCheckProject.getCheckProjectIds().split(",")).forEach(projectId -> {
            BizEnterCheckProject becp = new BizEnterCheckProject();
            BeanUtil.copyProperties(bizEnterCheckProject, becp);
            becp.setId(IdUtil.getSnowflakeNextId());
            becp.setCreateBy(user.getUserName());
            becp.setCreateTime(DateUtils.getNowDate());
            becp.setCheckProjectIds(projectId);

            if(StringUtils.isNotNull(becp.getPlanDate())){
                becp.setPlanStartTime(bizEnterCheckProject.getPlanDate()[0]);
                becp.setPlanEndTime(bizEnterCheckProject.getPlanDate()[1]);
            }

            bizEnterCheckProjectMapper.insertBizEnterCheckProject(becp);
            BizEnterTask task = new BizEnterTask();
            task.setId(IdUtil.getSnowflakeNextId());
            task.setBizEnterCheckId(becp.getBizEnterCheckId());
            task.setBizEnterCheckProjectId(becp.getId());
            task.setProjectId(Long.valueOf(projectId));
            task.setStatus("1");
            task.setCreateBy(user.getUserName());
            task.setCreateTime(DateUtils.getNowDate());
            bizEnterTaskMapper.insertBizEnterTask(task);
        });
    }

    /**
     * 修改企业检查-项目
     *
     * @param bizEnterCheckProject 企业检查-项目
     * @return 结果
     */
    @Override
    public int updateBizEnterCheckProject(BizEnterCheckProject bizEnterCheckProject, SysUser user)
    {
        bizEnterCheckProject.setUpdateBy(user.getUserName());
        bizEnterCheckProject.setUpdateTime(DateUtils.getNowDate());
        return bizEnterCheckProjectMapper.updateBizEnterCheckProject(bizEnterCheckProject);
    }

    /**
     * 批量删除企业检查-项目
     *
     * @param ids 需要删除的企业检查-项目主键
     * @return 结果
     */
    @Override
    public int deleteBizEnterCheckProjectByIds(Long[] ids)
    {
        return bizEnterCheckProjectMapper.deleteBizEnterCheckProjectByIds(ids);
    }

    /**
     * 删除企业检查-项目信息
     *
     * @param id 企业检查-项目主键
     * @return 结果
     */
    @Override
    public int deleteBizEnterCheckProjectById(Long id)
    {
        return bizEnterCheckProjectMapper.deleteBizEnterCheckProjectById(id);
    }

    /**
     * 根据企业检查id查询目录列表
     * @param id
     * @return
     */
    @Override
    public List<BizEnterCheckProject> selectProjectListByCheckId(Long id) {
        List<BizEnterCheckProject> bizEnterCheckProjectList = bizEnterCheckProjectMapper.selectProjectListByCheckId(id);
        setListParamNames(bizEnterCheckProjectList);
        return bizEnterCheckProjectList;
    }
}
